<script setup lang="ts">
import { ref, toRaw } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { useList, useTabs } from "@/hooks/page";
import {
  order_merge_list_api,
  offline_course_order_mini_pay_api,
  live_course_mini_pay_api,
} from "@/package/my/api/guider_home";
import {
  pay_api,
  get_product_buy_api,
  receiving_api,
} from "@/package/my/api/pass_port_order";
import { pay_api as pay_api2 } from "@/package/my/api/mini_app_tour_pay";
import { get_product_buy_api as get_product_buy_api2 } from "@/package/my/api/tour_order";
import { unifiedorder_api } from "@/package/my/api/groupon2";
import { EV_ORDER } from "@/constant/event";
import { Account } from "@/utils/account";
import { AppData } from "@/utils/app";
import { requestPayment } from "@/utils/payment";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import NavBack from "@/components/nav/back.vue";
import NavBar from "@/components/nav/bar.vue";
import FormPicker from "@/components/form/picker.vue";
import ListTabItem from "./components/list-tab-item.vue";
import ListEmpty from "@/components/list/empty.vue";
import ListOrderItem from "./components/list-order-item.vue";
import ListMore from "@/components/list/more.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  Account.checkLogin((isLogin) => {
    if (isLogin) Router.navigateBack();
    const index = Number(options?.type || 0);
    index === 0 ? tabChange({ detail: { current: 0 } }) : tabClick(index);

    uni.$on(EV_ORDER, evOrderCallback);
  });
});
onUnload(() => uni.$off(EV_ORDER, evOrderCallback));
const reloadData = () => {
  const index = tabData.index;
  if (index === 0) {
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(6) && reloadList7();
    tabCacheList.includes(7) && reloadList8();
    return reloadList();
  } else if (index === 1) {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(6) && reloadList7();
    tabCacheList.includes(7) && reloadList8();
    return reloadList2();
  } else if (index === 2) {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(6) && reloadList7();
    tabCacheList.includes(7) && reloadList8();
    return reloadList3();
  } else if (index === 3) {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(6) && reloadList7();
    tabCacheList.includes(7) && reloadList8();
    return reloadList4();
  } else if (index === 4) {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(6) && reloadList7();
    tabCacheList.includes(7) && reloadList8();
    return reloadList5();
  } else if (index === 5) {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(6) && reloadList7();
    tabCacheList.includes(7) && reloadList8();
    return reloadList6();
  } else if (index === 6) {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(7) && reloadList8();
    return reloadList7();
  } else {
    tabCacheList.includes(0) && reloadList();
    tabCacheList.includes(1) && reloadList2();
    tabCacheList.includes(2) && reloadList3();
    tabCacheList.includes(3) && reloadList4();
    tabCacheList.includes(4) && reloadList5();
    tabCacheList.includes(5) && reloadList6();
    tabCacheList.includes(6) && reloadList7();
    return reloadList8();
  }
};

const typeIndex = ref(0);
const typeList = [
  { id: 0, text: "全部" },
  { id: 1, text: "商品" },
  { id: 2, text: "线下培训" },
  { id: 3, text: "课程" },
  { id: 4, text: "直播课" },
  { id: 5, text: "人工讲解" },
  { id: 6, text: "文博讲解" },
];
const typeClick = (index: number) => {
  if (typeIndex.value === index) return;
  typeIndex.value = index;
  reloadData();
};

const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: 1, page_size: 10 }, (query) => {
    return order_merge_list_api({
      ...query,
      pay_status: 0,
      order_list_type: typeList[typeIndex.value].id,
    });
  });
const {
  listData: listData2,
  listStatus: listStatus2,
  listLoadMore: listLoadMore2,
  reloadList: reloadList2,
  loadMoreList: loadMoreList2,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 1,
    order_list_type: typeList[typeIndex.value].id,
  });
});
const {
  listData: listData3,
  listStatus: listStatus3,
  listLoadMore: listLoadMore3,
  reloadList: reloadList3,
  loadMoreList: loadMoreList3,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 2,
    order_list_type: typeList[typeIndex.value].id,
  });
});
const {
  listData: listData4,
  listStatus: listStatus4,
  listLoadMore: listLoadMore4,
  reloadList: reloadList4,
  loadMoreList: loadMoreList4,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 3,
    order_list_type: typeList[typeIndex.value].id,
  });
});
const {
  listData: listData5,
  listStatus: listStatus5,
  listLoadMore: listLoadMore5,
  reloadList: reloadList5,
  loadMoreList: loadMoreList5,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 4,
    order_list_type: typeList[typeIndex.value].id,
  });
});
const {
  listData: listData6,
  listStatus: listStatus6,
  listLoadMore: listLoadMore6,
  reloadList: reloadList6,
  loadMoreList: loadMoreList6,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 5,
    order_list_type: typeList[typeIndex.value].id,
  });
});
const {
  listData: listData7,
  listStatus: listStatus7,
  listLoadMore: listLoadMore7,
  reloadList: reloadList7,
  loadMoreList: loadMoreList7,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 6,
    order_list_type: typeList[typeIndex.value].id,
  });
});
const {
  listData: listData8,
  listStatus: listStatus8,
  listLoadMore: listLoadMore8,
  reloadList: reloadList8,
  loadMoreList: loadMoreList8,
} = useList({ page: 1, page_size: 10 }, (query) => {
  return order_merge_list_api({
    ...query,
    pay_status: 7,
    order_list_type: typeList[typeIndex.value].id,
  });
});

const tabList = [
  "全部",
  "待付款",
  "已付款",
  "待评价",
  "超时未支付",
  "已退款",
  "已发货",
  "已完成",
];
const { tabData, tabCacheList, tabClick, tabChange } = useTabs(
  (index: number) => {
    index === 0
      ? reloadList()
      : index === 1
      ? reloadList2()
      : index === 2
      ? reloadList3()
      : index === 3
      ? reloadList4()
      : index === 4
      ? reloadList5()
      : index === 5
      ? reloadList6()
      : index === 6
      ? reloadList7()
      : reloadList8();
  }
);

const orderClick = (
  type: "pay" | "again" | "receive" | "copy" | "explain",
  index: number
) => {
  const _tabIndex = tabData.index;
  const _listData =
    _tabIndex === 7
      ? listData8.value
      : _tabIndex === 6
      ? listData7.value
      : _tabIndex === 5
      ? listData6.value
      : _tabIndex === 4
      ? listData5.value
      : _tabIndex === 3
      ? listData4.value
      : _tabIndex === 2
      ? listData3.value
      : _tabIndex === 1
      ? listData2.value
      : listData.value;

  const item = toRaw(_listData)[index] as any;
  type === "pay"
    ? payClick(item)
    : type === "again"
    ? againClick(item)
    : type === "receive"
    ? receiveClick(item.id)
    : type === "copy"
    ? copyClick(item.express_out_trade_no)
    : type === "explain"
    ? explainClick(item)
    : detailClick(item);
};

const payClick = (obj: any) => {
  Toast.showLoading();
  if (obj.order_list_type === 1) {
    pay_api({ order_id: obj.id })
      .then((resp) => {
        Toast.hideLoading();
        requestPayment(resp, () => {
          uni.$emit(EV_ORDER, {
            type: "pay",
            data: { type: "goods", id: obj.id },
          });
        });
      })
      .catch(() => Toast.hideLoading());
  } else if (obj.order_list_type === 2) {
    offline_course_order_mini_pay_api({ order_id: obj.id })
      .then((resp) => {
        Toast.hideLoading();
        requestPayment(resp, () => {
          uni.$emit(EV_ORDER, {
            type: "pay",
            data: { type: "train", id: obj.id },
          });
        });
      })
      .catch(() => Toast.hideLoading());
  } else if (obj.order_list_type === 3) {
    unifiedorder_api({ order_id: obj.id, pay_type: 1, pay_from: "miniprogram" })
      .then((resp) => {
        Toast.hideLoading();
        requestPayment(resp, () => {
          uni.$emit(EV_ORDER, {
            type: "pay",
            data: { type: "course", id: obj.id },
          });
        });
      })
      .catch(() => Toast.hideLoading());
  } else if (obj.order_list_type === 4) {
    live_course_mini_pay_api({ order_id: obj.id })
      .then((resp) => {
        Toast.hideLoading();
        requestPayment(resp, () => {
          uni.$emit(EV_ORDER, {
            type: "pay",
            data: { type: "live", id: obj.id },
          });
        });
      })
      .catch(() => Toast.hideLoading());
  } else {
    pay_api2({ pre_order_id: obj.id })
      .then((resp) => {
        Toast.hideLoading();
        requestPayment(resp, () => {
          uni.$emit(EV_ORDER, {
            type: "pay",
            data: { type: "jps", id: obj.id },
          });
        });
      })
      .catch(() => Toast.hideLoading());
  }
};
const againClick = (obj: any) => {
  if (obj.order_list_type === 1) {
    get_product_buy_api({ order_id: obj.id }).then((resp) => {
      resp.product_status === 1
        ? Router.navigateTo(
            `/package/mall/pages/goods/detail?id=${resp.product_id}`
          )
        : Toast.show("产品已下架或删除，去看看别的产品吧");
    });
  } else {
    get_product_buy_api2({ order_id: obj.id }).then((resp) => {
      resp.product_status === 1
        ? Router.navigateTo(
            `/package/mall/pages/jps/detail?id=${resp.product_id}`
          )
        : Toast.show("产品已下架或删除，去看看别的产品吧");
    });
  }
};
const receiveClick = (id: string) => {
  popupModal.value?.show(
    {
      title: "确认收货",
      content: "您是否已确认收到货物？为保障售后权益，请收货后再确认。",
    },
    () => {
      Toast.showLoading();
      receiving_api({ order_id: id })
        .then(() => {
          Toast.hideLoading();
          uni.$emit(EV_ORDER, { type: "receive", data: { type: "shop", id } });
        })
        .catch(() => Toast.hideLoading());
    }
  );
};
const copyClick = (data: string) => {
  uni.setClipboardData({ data });
};
const explainClick = (obj: any) => {
  Router.navigateToMiniProgram(obj.app_id, obj.jump_path);
};
const detailClick = (obj: any) => {
  Router.navigateTo(
    obj.order_list_type === 3
      ? `/package/study/pages/course/detail?id=${obj.product_no}`
      : `/package/my/pages/order/detail?id=${obj.id}&type=${obj.order_list_type}`
  );
};

const evOrderCallback = (e: { type: "" }) => {
  console.info(`触发事件：${EV_ORDER}`, e);
  reloadData();
};

const popupModal = ref<InstanceType<typeof PopupModal>>();
</script>

<template>
  <NavBack />
  <NavBar position="relative" background="#ffffff">
    <FormPicker
      v-model="typeIndex"
      :range="typeList"
      rangeKey="text"
      @change="reloadData"
    >
      <view class="list-nav">
        <view class="list-nav-title">{{ typeList[typeIndex].text }}订单</view>
        <image
          class="list-nav-icon"
          src="@/package/my/static/order-list-more.png"
        />
      </view>
    </FormPicker>
  </NavBar>

  <scroll-view class="list-tab" scroll-x enhanced :show-scrollbar="false">
    <view class="list-tab-space"></view>
    <view
      class="list-tab-item"
      v-for="(i, d) of tabList"
      :key="d"
      @click="tabClick(d)"
    >
      <ListTabItem :isActive="tabData.index === d" :text="i" />
    </view>
  </scroll-view>

  <swiper
    :current="tabData.current"
    :style="{
      height: `calc(100vh - ${AppData.rectData.topBarHeight}px - 90rpx)`,
    }"
    @change="tabChange"
  >
    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore = true"
        @scrolltolower="loadMoreList"
      >
        <ListEmpty v-if="listData.length === 0 && listStatus === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore"
            :status="listStatus"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore2 = true"
        @scrolltolower="loadMoreList2"
      >
        <ListEmpty v-if="listData2.length === 0 && listStatus2 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData2"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore2"
            :status="listStatus2"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore3 = true"
        @scrolltolower="loadMoreList3"
      >
        <ListEmpty v-if="listData3.length === 0 && listStatus3 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData3"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore3"
            :status="listStatus3"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore4 = true"
        @scrolltolower="loadMoreList4"
      >
        <ListEmpty v-if="listData4.length === 0 && listStatus4 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData4"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore4"
            :status="listStatus4"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore5 = true"
        @scrolltolower="loadMoreList5"
      >
        <ListEmpty v-if="listData5.length === 0 && listStatus5 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData5"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore5"
            :status="listStatus5"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore6 = true"
        @scrolltolower="loadMoreList6"
      >
        <ListEmpty v-if="listData6.length === 0 && listStatus6 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData6"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore6"
            :status="listStatus6"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore7 = true"
        @scrolltolower="loadMoreList7"
      >
        <ListEmpty v-if="listData7.length === 0 && listStatus7 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData7"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore7"
            :status="listStatus7"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="list-data"
        scroll-y
        @scroll="listLoadMore8 = true"
        @scrolltolower="loadMoreList8"
      >
        <ListEmpty v-if="listData8.length === 0 && listStatus8 === 'noMore'" />
        <template v-else>
          <view class="list-data-wrapper">
            <view
              class="list-data-item"
              v-for="(i, d) of listData8"
              :key="i.id"
              @click="orderClick('', d)"
            >
              <ListOrderItem :info="i" @btn-click="(e) => orderClick(e, d)" />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore8"
            :status="listStatus8"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>
  </swiper>
</template>

<style lang="scss">
page {
  padding-bottom: 0;
}

.list-nav {
  position: absolute;
  left: 50%;
  top: 50%;
  display: flex;
  align-items: center;
  transform: translate(-50%, -50%);

  .list-nav-title {
    margin-right: 10rpx;
    font-size: 16px;
    color: #333333;
    line-height: 20px;
    font-weight: bold;
  }

  .list-nav-icon {
    width: 34rpx;
    height: 34rpx;
  }
}

.list-tab {
  width: 100vw;
  height: 90rpx;
  white-space: nowrap;
  background-color: #ffffff;

  .list-tab-space,
  .list-tab-item {
    display: inline-block;
    margin-top: 4rpx;
    vertical-align: top;
  }

  .list-tab-space {
    width: 30rpx;
  }

  .list-tab-item {
    margin-right: 60rpx;
  }
}

.list-data {
  height: 100%;

  .list-data-wrapper {
    padding-top: 20rpx;
  }

  .list-data-item {
    margin: 0 30rpx 20rpx;
  }
}
</style>